const express = require('express');
const path = require('path');
const fs = require('fs-extra');
const crypto = require('crypto');
const config = require('../config/server');

const router = express.Router();

// 资源清单
const resourceManifest = {
    "SolarPower": "SolarPower/SolarPower.html",
    "VoiceInteractiveMap": "VoiceInteractiveMap/VoiceInteractiveMap.html",
    "TurbofanEngine": "TurbofanEngine/TurbofanEngine.html",
    "Hannault": "Hannault/index.html",
    "fossil": "fossil/index.html",
    "KimAqQarav": "KimAqQarav/index.html",
    "mineral": "mineral/index.html",
    "Lightnin_Glow": "Lightnin_Glow/index.html",
    "Crooks_Radiometer": "Crooks_Radiometer/index.html",
    "Manipulator": "Manipulator/index.html",
    "Remote_Piano": "Remote_Piano/index.html",
    "Fun_Beginner_AI": "Fun_Beginner_AI/index.html",
    "Specimen_Wheat": "Specimen_Wheat/index.html",
    "Specimen_Soil": "Specimen_Soil/index.html",
    "Specimen_Silkworm": "Specimen_Silkworm/index.html",
    "Specimen_Dragonfly": "Specimen_Dragonfly/index.html",
    "Specimens_FoodCrops": "Specimens_FoodCrops/index.html",
    "Specimens_Arthropods": "Specimens_Arthropods/index.html",
    "specimen_beanSprouts": "specimen_beanSprouts/index.html"
};

// 计算文件哈希值
async function calculateFileHash(filePath) {
    try {
        const fileBuffer = await fs.readFile(filePath);
        return crypto.createHash('md5').update(fileBuffer).digest('hex');
    } catch (error) {
        console.error('计算文件哈希失败:', filePath, error);
        return null;
    }
}

// 扫描资源目录并生成版本信息
async function generateVersionInfo() {
    const versionInfo = {
        version: config.version.defaultVersion,
        timestamp: new Date().toISOString(),
        resources: {},
        totalSize: 0,
        totalFiles: 0
    };
    
    try {
        for (const [key, relativePath] of Object.entries(resourceManifest)) {
            const fullPath = path.join(config.staticPath, relativePath);
            
            if (await fs.pathExists(fullPath)) {
                const stats = await fs.stat(fullPath);
                const hash = await calculateFileHash(fullPath);
                
                versionInfo.resources[key] = {
                    path: relativePath,
                    size: stats.size,
                    hash: hash,
                    lastModified: stats.mtime.toISOString()
                };
                
                versionInfo.totalSize += stats.size;
                versionInfo.totalFiles++;
            }
        }
        
        // 计算总体哈希值
        const allHashes = Object.values(versionInfo.resources)
            .map(r => r.hash)
            .filter(h => h)
            .sort()
            .join('');
        
        versionInfo.overallHash = crypto.createHash('md5').update(allHashes).digest('hex');
        
    } catch (error) {
        console.error('生成版本信息失败:', error);
    }
    
    return versionInfo;
}

// 获取版本信息
router.get('/version', async (req, res, next) => {
    try {
        const versionInfo = await generateVersionInfo();
        res.json(versionInfo);
    } catch (error) {
        console.error('获取版本信息失败:', error);
        next(error);
    }
});

// 获取资源列表
router.get('/resources', async (req, res, next) => {
    try {
        const versionInfo = await generateVersionInfo();
        res.json({
            resources: versionInfo.resources,
            totalFiles: versionInfo.totalFiles,
            totalSize: versionInfo.totalSize,
            timestamp: versionInfo.timestamp
        });
    } catch (error) {
        console.error('获取资源列表失败:', error);
        next(error);
    }
});

// 检查特定资源是否存在
router.get('/check/:resourceKey', async (req, res, next) => {
    try {
        const { resourceKey } = req.params;
        
        if (!resourceManifest[resourceKey]) {
            return res.status(404).json({
                error: '资源不存在',
                resourceKey: resourceKey
            });
        }
        
        const relativePath = resourceManifest[resourceKey];
        const fullPath = path.join(config.staticPath, relativePath);
        
        if (await fs.pathExists(fullPath)) {
            const stats = await fs.stat(fullPath);
            const hash = await calculateFileHash(fullPath);
            
            res.json({
                exists: true,
                resourceKey: resourceKey,
                path: relativePath,
                size: stats.size,
                hash: hash,
                lastModified: stats.mtime.toISOString()
            });
        } else {
            res.json({
                exists: false,
                resourceKey: resourceKey,
                path: relativePath
            });
        }
    } catch (error) {
        console.error('检查资源失败:', error);
        next(error);
    }
});

// 批量检查资源
router.post('/check-batch', async (req, res, next) => {
    try {
        const { resourceKeys } = req.body;
        
        if (!Array.isArray(resourceKeys)) {
            return res.status(400).json({
                error: 'resourceKeys必须是数组'
            });
        }
        
        const results = {};
        
        for (const resourceKey of resourceKeys) {
            if (resourceManifest[resourceKey]) {
                const relativePath = resourceManifest[resourceKey];
                const fullPath = path.join(config.staticPath, relativePath);
                
                if (await fs.pathExists(fullPath)) {
                    const stats = await fs.stat(fullPath);
                    const hash = await calculateFileHash(fullPath);
                    
                    results[resourceKey] = {
                        exists: true,
                        path: relativePath,
                        size: stats.size,
                        hash: hash,
                        lastModified: stats.mtime.toISOString()
                    };
                } else {
                    results[resourceKey] = {
                        exists: false,
                        path: relativePath
                    };
                }
            } else {
                results[resourceKey] = {
                    exists: false,
                    error: '资源不存在'
                };
            }
        }
        
        res.json({
            results: results,
            timestamp: new Date().toISOString()
        });
    } catch (error) {
        console.error('批量检查资源失败:', error);
        next(error);
    }
});

module.exports = router;
